package com.myproject.weather.weatherInfo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

public class HttpUtil {

	public static void setHttpProxy(String host, String port, String user, String password) {
		System.setProperty("proxySet", "true");
		System.setProperty("http.proxyHost", host);
		System.setProperty("http.proxyPort", port);
		Authenticator.setDefault(new BaseAuthenticator(user, password));
	}

	public static void removeHttpProxy() {
		System.setProperty("proxySet", "false");
		System.getProperties().remove("http.proxyHost");
		System.getProperties().remove("http.proxyPort");
		Authenticator.setDefault(null);
	}

	public static void main(String[] args) throws Exception {
		setHttpProxy("10.195.113.100", "8002", "c_yangrui-006", "Cpic4321");
		getData("http://www.weather.com.cn/data/sk/101020100.html");
	}

	public static String getData(String url) throws IOException, MalformedURLException {
		String result = null;
		char[] buff = new char[50];
		InputStreamReader in = new InputStreamReader(new URL(url).openStream(), "UTF-8");
		StringBuilder builder = new StringBuilder();
		int offset = 0;
		int read = 0;
		while ((read = in.read(buff, offset, 50)) != -1) {
			builder.append(buff, 0, read);
		}
		result = builder.toString();
		return result;
	}

	static class BaseAuthenticator extends Authenticator {
		private String user;
		private char[] password;

		public BaseAuthenticator(String user, String password) {
			this.user = user;
			this.password = password.toCharArray();
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	}

}
